/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved.
 * Description: 获取动态库中tdt接口函数的适配接口
 * Author: lzd
 * Create: 2020-06-10
 */

#include <string>
#include <map>
#include "hccl_dl.h"
#include "dltdt_function.h"
#include "log.h"

namespace hccl {
DlTdtFunction &DlTdtFunction::GetInstance()
{
    static DlTdtFunction hcclDlTdtFunction;
    return hcclDlTdtFunction;
}

DlTdtFunction::DlTdtFunction() : handle_(nullptr)
{
}

DlTdtFunction::~DlTdtFunction()
{
    if (handle_ != nullptr) {
        (void)HcclDlclose(handle_);
        handle_ = nullptr;
    }
}
HcclResult DlTdtFunction::DlTdtFunctionInit()
{
#ifndef HCCD
    std::lock_guard<std::mutex> lock(handleMutex_);
    if (handle_ == nullptr) {
        handle_ = HcclDlopen("libtsdclient.so", RTLD_NOW);
        const char* errMsg = dlerror();
        CHK_PRT_RET(handle_ == nullptr, HCCL_ERROR("dlopen [%s] failed, %s", "libtsdclient.so",\
            (errMsg == nullptr) ? "please check the file exist or permission denied." : errMsg),\
            HCCL_E_OPEN_FILE_FAILURE);
    }
    dlTsdOpen = (tsd::TSD_StatusT(*)(u32 deviceLogicId, u32 rankSize))HcclDlsym(handle_, "TsdOpen");
    CHK_SMART_PTR_NULL(dlTsdOpen);
    dlTsdCapabilityGet = (tsd::TSD_StatusT(*)(uint32_t deviceLogicId, int32_t type, uint64_t ptr))\
        HcclDlsym(handle_, "TsdCapabilityGet");
    CHK_SMART_PTR_NULL(dlTsdCapabilityGet);
    dlTsdProcessOpen = (tsd::TSD_StatusT(*)(u32 deviceLogicId, ProcOpenArgs *openArgs))\
        HcclDlsym(handle_, "TsdProcessOpen");
    CHK_SMART_PTR_NULL(dlTsdProcessOpen);
    dlProcessCloseSubProcList = (tsd::TSD_StatusT(*)(u32 deviceLogicId, ProcStatusParam *closeList, u32 listSize))\
        HcclDlsym(handle_, "ProcessCloseSubProcList");
    CHK_SMART_PTR_NULL(dlProcessCloseSubProcList);
    return HCCL_SUCCESS;
#else
    HCCL_ERROR("[DlTdtFunctionInit]Does not support this interface.");
    return HCCL_E_NOT_SUPPORT;
#endif
}

HcclResult DlTdtFunction::DlTdtFunctionHeterogInit()
{
    std::lock_guard<std::mutex> lock(handleMutex_);
    if (handle_ == nullptr) {
        handle_ = HcclDlopen("libtsdclient.so", RTLD_NOW);
        const char* errMsg = dlerror();
        CHK_PRT_RET(handle_ == nullptr, HCCL_ERROR("dlopen [%s] failed, %s", "libtsdclient.so",\
            (errMsg == nullptr) ? "please check the file exist or permission denied." : errMsg),\
            HCCL_E_OPEN_FILE_FAILURE);
    }
    dlTsdProcessOpen = (tsd::TSD_StatusT(*)(u32 deviceLogicId, ProcOpenArgs *openArgs))\
        HcclDlsym(handle_, "TsdProcessOpen");
    CHK_SMART_PTR_NULL(dlTsdProcessOpen);
    dlProcessCloseSubProcList = (tsd::TSD_StatusT(*)(u32 deviceLogicId, ProcStatusParam *closeList, u32 listSize))\
        HcclDlsym(handle_, "ProcessCloseSubProcList");
    CHK_SMART_PTR_NULL(dlProcessCloseSubProcList);
    return HCCL_SUCCESS;
}

}
